package cn.study.base;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 使用函数引用简单实现disruptor运用
 *
 * @Author: 陈胜
 * @Date: 2018/2/26 14:51
 */
public class LongEventMainMethodRef {
    public static void handleEvent(LongEvent event, long sequence, boolean endOfBatch) {
        System.out.println("customer: " + event.getValue());
    }

    public static void translate(LongEvent event, long sequence, ByteBuffer buffer) {
        event.setValue(buffer.getLong(0));
        System.out.println("producer: " + event.getValue());
    }

    public static void main(String[] args) throws Exception {
        // 创建缓冲线程池
        Executor executor = Executors.newCachedThreadPool();
        // 创建bRingBuffer大小，2的N次方
        int bufferSize = 1024;

        // 创建Disruptor实例
        Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new, bufferSize, executor);
        /**
         * 连接消费事件方法
         *
         * 用函数引用，实现消费者业务逻辑处理
         */

        disruptor.handleEventsWith(LongEventMainMethodRef::handleEvent);
        // 启动disruptor
        disruptor.start();
        // 发布事件（获取存放数据的容器）
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        // 实例化生产者
        //LongEventProducer producer = new LongEventProducer(ringBuffer);

        ByteBuffer bb = ByteBuffer.allocate(8);
        for (long l = 0; true; l++) {
            bb.putLong(0, l);
            // 用函数引用，实现生产者业务逻辑处理
            ringBuffer.publishEvent(LongEventMainMethodRef::translate, bb);
            Thread.sleep(1000);
        }
    }
}
